package cn.donting.web.desktop.sys.push;


import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.sys.service.UserCenter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.util.HashMap;

//@Component
@Slf4j
//@ServerEndpoint(value = "/sys/desktop/push", configurator = PushWebsocket.Configurator.class)
public class PushWebsocket {

    class Configurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            HttpSession httpSession = (HttpSession) request.getHttpSession();
            sec.getUserProperties().put("httpSession", httpSession);
        }
    }

    private static HashMap<User, PushWebsocket> desktopPush = new HashMap<>();
    private static UserCenter userCenter;

    private ObjectMapper objectMapper = new ObjectMapper();

    //隶属谁
    private User user = null;
    private Session session;

    @Autowired
    public void setUserCenter(UserCenter userCenter) {
        PushWebsocket.userCenter = userCenter;
    }

    @OnOpen
    public void onOpen(Session session) {
        HttpSession httpSession = (HttpSession) session.getUserProperties().get("httpSession");
        String sessionId = httpSession.getId();
        User loginUser = userCenter.getLoginUser(sessionId);
        this.user = loginUser;
        desktopPush.put(user, this);
        this.session = session;
    }

    @OnClose
    public void onClose(Session session){
        PushWebsocket remove = desktopPush.remove(user);
        log.info(user.getName()+" PushWebsocket onClose");
    }
    @OnError
    public void onError(Session session,Throwable throwable){
        log.error(user.getName()+" PushWebsocket onError");
        log.error(throwable.getMessage(),throwable);
    }


    public void sendMsg(PushMsg pushMsg) throws Exception {
        String msg = objectMapper.writeValueAsString(pushMsg);
        session.getBasicRemote().sendText(msg);
    }


    public static PushWebsocket getPushWebsocket(User user){
        PushWebsocket pushWebsocket = desktopPush.get(user);
        return pushWebsocket;
    }


}
